#coding=utf-8
# Copyright 2011 Kirill Gagarski <gagarin.gtn@gmail.com>
# Copyright 2012 Maxim Petrov <maximpetrov@yahoo.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 3 or any later version.

from modal_window import ModalWindow
from controls import TextField, PasswordField, Button, Label, split_string
import curses.ascii
import math
class OKCancelWindow(ModalWindow):
    """Modal window with text and OK/Cancel buttons"""

    # Redefine ModalWindow constants
    _SHOULD_ENLARGE = False
    _message_visible = True
    _EXIT_BUTTON = u'Cancel'
    __MIN_TEXT_WIDTH = 8

    _OK = _(u'OK')
    _CANCEL = _(u'Cancel')

    def __init__(self, text, title=u"?"):
        """
        Constructor.

        Keywords arguments:
            text - Displayed text
            title - Window title
        """

        self._title = title
        # Active control
        buttons_width = (max(len(OKCancelWindow._OK), len(OKCancelWindow._CANCEL)) +\
                        4) * 2
        self._PREFERRED_MIN_WIDTH = buttons_width + 2
        self._MIN_WIDTH = buttons_width + 2

        line_w = self._PREFERRED_MIN_WIDTH - 4
        self._MIN_HEIGHT = len(split_string(text, line_w)) + 4
        self._PREFERRED_MIN_HEIGHT = self._MIN_HEIGHT
        self.__message_label = Label(None, lambda w, h: (2, 1, w - 4, None), text, True)
        self.__ok_button = Button(None, lambda w, h: \
            (w / 4 - len(OKCancelWindow._OK) / 2, h - 2, None, None),
            self._OK)
        self.__cancel_button = Button(None, lambda w, h: \
            (w * 3 / 4 - len(OKCancelWindow._CANCEL) / 2 - 1, h - 2, None, None),
            self._CANCEL)
        # Label and buttons
        self._controls = [(self.__ok_button, True), (self.__cancel_button, True),
                           (self.__message_label, False)]

    def handle_keypress(self, ch, uni):
        """
        Function handle keypress.

        Keywords arguments:
            ch - pressed key
            uni - True if ch is Unicode char, False otherwise

        Return value:
            Return dictionary contains pressed button if this keypress results
            closing window, otherwise return None
        """

        result = ModalWindow.handle_keypress(self, ch, uni)
        if result is not None:
            return result
        if ch == ord('\n'):
            if self._selected == self.__ok_button:
                return {u'button': u'OK'}
            elif self._selected == self.__cancel_button:
                return {u'button': u'Cancel'}
        elif ch == ord('\t'):
            self._next_control()
        else:
            self._selected.handle_keypress(ch, uni)
